package common.util.mybatis.plus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import common.util.mybatis.plus.logic.LogicBaseField;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @author 刘波
 */
public class LogicMetaObjectHandler implements MetaObjectHandler {

	private LogicMetaObjectHandlerService logicMetaObjectHandlerService;

	public LogicMetaObjectHandler(LogicMetaObjectHandlerService logicMetaObjectHandlerService) {
		super();
		this.logicMetaObjectHandlerService = logicMetaObjectHandlerService;
	}

	@Override
	public void insertFill(MetaObject metaObject) {
		Object createTime = getFieldValByName(LogicBaseField.createTime, metaObject);
		if (null == createTime) {
			setFieldValByName(LogicBaseField.createTime, new Date(), metaObject);
		}
		Object modifyTime = getFieldValByName(LogicBaseField.modifyTime, metaObject);
		if (null == modifyTime) {
			setFieldValByName(LogicBaseField.modifyTime, new Date(), metaObject);
		}
		Object version = getFieldValByName(LogicBaseField.version, metaObject);
		if (null == version) {
			setFieldValByName(LogicBaseField.version, 0, metaObject);
		}
		Object removed = getFieldValByName(LogicBaseField.removed, metaObject);
		if (null == removed) {
			setFieldValByName(LogicBaseField.removed, 0, metaObject);
		}
		Object createUser = getFieldValByName(LogicBaseField.createUser, metaObject);
		String operator = logicMetaObjectHandlerService.getOperator();
		if(null == createUser) {
			setFieldValByName(LogicBaseField.createUser, operator , metaObject);
		}
		Object modifyUser = getFieldValByName(LogicBaseField.modifyUser, metaObject);
		if(null == modifyUser) {
			setFieldValByName(LogicBaseField.modifyUser, operator , metaObject);
		}
	}


	@Override
	public void updateFill(MetaObject metaObject) {
		String operator = logicMetaObjectHandlerService.getOperator();
		Object modifyTime = getFieldValByName(LogicBaseField.modifyTime, metaObject);
		if (null == modifyTime) {
			setFieldValByName(LogicBaseField.modifyTime, new Date(), metaObject);
		}
		Object modifyUser = getFieldValByName(LogicBaseField.modifyUser, metaObject);
		if(null == modifyUser) {
			setFieldValByName(LogicBaseField.modifyUser, operator , metaObject);
		}
	}

}
